//
//  String+Extension.swift
//  TodayNews
//
//  Created by 杨蒙 on 2017/6/16.
//  Copyright © 2017年 hrscy. All rights reserved.
//

import UIKit
/**
 字符串与字符的连接
 let char1:Character="o"
 var str1="hell"
 let str2=str1+String(char1)
 //str2="hello"
 //----------------------------------------
 let str3="\(str1)\(char1)"
 //str3="hello"
 //----------------------------------------
 str1.append(char1)
 //str1="hello"
 **/

/**
 let strArray=["apple", "orange", "cherry"]
 let joinStr=",".join(strArray)
 //joinStr="apple,orange,cherry"
 **/

extension String {
    subscript (range: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
            return String(self[Range(startIndex..<endIndex)])
        }
        
        set {
            let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
            let strRange = Range(startIndex..<endIndex)
            self.replaceSubrange(strRange, with: newValue)
        }
    }
    static func isBankString (String string:String) -> Bool {
        if string.isEmpty {
            return true
        }
        else
        {
            //去掉空格和换行
            //            let str2=string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            let charset=CharacterSet.init(charactersIn: " \n")
            let str2=string.trimmingCharacters(in: charset)
            return str2.isEmpty
        }
        
    }
    
    //富文本
    static func changeToAttributeStringWith(String string:String, IndexOfString index:Int, LengthOfString length:Int,  StringFont font:CGFloat, StringColor color:UIColor) -> NSMutableAttributedString{
        let attriString = NSMutableAttributedString(string: string)
        attriString.addAttribute(.font, value: UIFont.systemFont(ofSize: font), range: NSMakeRange(index, length))
        attriString.addAttribute(.foregroundColor, value: color, range: NSMakeRange(index, length))
        return attriString
    }
    
    //判断字符串条件 1:数字 2:英文 3:符合的英文+数字
    static func isHaveNumAndLetter(String string:String) -> Int {
        do {
            let tNumRegularExpression =  try NSRegularExpression.init(pattern: "[0-9]", options: .caseInsensitive)
            let tNumMatchCount:Int = tNumRegularExpression.numberOfMatches(in: string, options: .reportProgress, range: NSMakeRange(0, string.count))
            
            let tLetterRegularExpression = try NSRegularExpression.init(pattern: "[A-Za-z]", options: .caseInsensitive)
            let tLetterMatchCount:Int = tLetterRegularExpression.numberOfMatches(in: string, options: .reportProgress, range: NSMakeRange(0, string.count))
            
            if tNumMatchCount == string.count {
                return 1
            }else if tLetterMatchCount == string.count {
                return 2
            }else if tNumMatchCount + tLetterMatchCount == string.count {
                return 3
            }else{
                return 4
            }
        }catch{return 0}
    }
    
    
    
    /// 计算文本的高度
    func getTextHeight(width: CGFloat) -> CGFloat {
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        return (self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 16)], context: nil).size.height)
    }
    
    
    
    //    //MD5加密
    //     func md5(Str str:String) -> String{
    //        let cStr = str.cString(using: String.Encoding.utf8)
    //        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
    //        CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
    //        let md5String = NSMutableString();
    //        for i in 0 ..< 16{
    //            md5String.appendFormat("%02x", buffer[i])
    //        }
    //        free(buffer)
    //        return md5String as String
    //    }
    
    //base64加密
    static func encodingBase64(String str:String) -> String{
        let data = str.data(using: String.Encoding.utf8)
        return (data?.base64EncodedString(options: .lineLength64Characters))!
    }
    
    
    
    //json 转 字典
    
    static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
    
    // 字典 转 json
    static func convertDictionaryToString(dict:[String:AnyObject]) -> String {
        var result:String = ""
        do {
            //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.init(rawValue: 0))
            
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                result = JSONString
            }
            
        } catch {
            result = ""
        }
        return result
    }
    
    // 数组 转 json
    static func convertArrayToString(arr:[AnyObject]) -> String {
        var result:String = ""
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.init(rawValue: 0))
            
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                result = JSONString
            }
            
        } catch {
            result = ""
        }
        return result
    }
    // string 转 数组
    
    func toArrayWith(string:String) -> [String]? {
        let charset=CharacterSet.init(charactersIn:",")
        let strArray = self.components(separatedBy: charset)
        // 也可以返回 数组
        //        let splitStr = self.split(separator: ",")
        
        return strArray
        
    }
    
}



